package cn.net.lwj.common.util;

import cn.net.lwj.common.exception.SjtbException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * setConnectionRequestTimeout：从连接管理池中获取连接的超时时间，这个是 HttpClient 连接池管理的参数，未设置且没有可用连接时将导致无限等待；
 * setConnectTimeout：与服务器建立链接的超时时间，网站不挂的话，基本OK；
 * setSocketTimeout ：从服务器获取响应数据的超时时间，a maximum period inactivity between two consecutive data packets 。这个是关键指标，指在等待读取数据时两次连续数据包之间等待的最大时间间隔。
 */
public class HttpClientUtils {

    // 编码格式。发送编码格式统一用UTF-8
    private static final String ENCODING = "UTF-8";

    // 设置连接超时时间，单位毫秒。
    private static final int CONNECT_TIMEOUT = 30000;

    // 请求获取数据的超时时间(即响应时间)，单位毫秒。
    private static final int SOCKET_TIMEOUT = 60000;

    private static final int CONNECTION_REQUEST_TIMEOUT = 120000;

    /**
     * 发送get请求；不带请求头和请求参数
     *
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static String doGet(String url) throws Exception {
        return doGet(url, null, null);
    }

    /**
     * 发送get请求；带请求参数
     *
     * @param url    请求地址
     * @param params 请求参数集合
     * @return
     * @throws Exception
     */
    public static String doGet(String url, Map<String, String> params) throws Exception {
        return doGet(url, null, params);
    }

    /**
     * 发送get请求；带请求参数
     *
     * @param url    请求地址
     * @param params 请求参数字符串  直接追加在url后面
     * @return
     * @throws Exception
     */
    public static String doGet(String url, String params) throws Exception {
        return doGet(url + "?" + params, null, null);
    }

    public static String doGetStr(String url, Map<String, String> headers, String params) throws Exception {
        return doGet(url + "?" + params, headers, null);
    }


    /**
     * 发送get请求；带请求头和请求参数
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  请求参数集合
     * @return
     * @throws Exception
     */
    public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建访问的地址
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }

        // 创建http对象
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        /**
         * setConnectTimeout：设置连接超时时间，单位毫秒。
         * setConnectionRequestTimeout：设置从connect Manager(连接池)获取Connection
         * 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
         * setSocketTimeout：请求获取数据的超时时间(即响应时间)，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpGet.setConfig(requestConfig);

        // 设置请求头
        packageHeader(headers, httpGet);

        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;

        try {
            // 执行请求并获得响应结果
            return getHttpClientResult(httpClient, httpGet);
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
        }
    }



    /**
     * 发送post请求；不带请求头和请求参数
     *
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static String doPost(String url) throws Exception {
        return doPost(url, null, null);
    }

    /**
     * urlParams组装到url里面
     *
     * @param url
     * @param urlParams
     * @return
     * @throws Exception
     */
    public static String doPost(String url, String urlParams) throws Exception {
        return doPost(url + "?" + urlParams, null, null);
    }

    /**
     * 发送post请求；带请求参数
     *
     * @param url    请求地址
     * @param params 参数集合
     * @return
     * @throws Exception
     */
    public static String doPost(String url, Map<String, String> params) throws Exception {
        return doPost(url, null, params);
    }

    public static String doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        return doPost(url, headers, params, null);
    }

    /**
     * 发送post请求；带请求头和请求参数
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  请求参数集合
     * @return
     * @throws Exception
     */
    public static String doPost(String url, Map<String, String> headers, Map<String, String> params, String jsonParam) throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建http对象
        HttpPost httpPost = new HttpPost(url);
        /**
         * setConnectTimeout：设置连接超时时间，单位毫秒。
         * setConnectionRequestTimeout：设置从connect Manager(连接池)获取Connection
         * 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
         * setSocketTimeout：请求获取数据的超时时间(即响应时间)，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPost.setConfig(requestConfig);
        //通用请求头
        httpPost.addHeader("encoding", "UTF-8");
        httpPost.addHeader("content-type", "application/json; charset=utf-8");
        // 设置请求头
		/*httpPost.setHeader("Cookie", "");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
		httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
        packageHeader(headers, httpPost);

        // 封装请求参数
        packageParam(params, httpPost);

        //body请求参数
        httpPost.setEntity(new StringEntity(jsonParam, ENCODING));

        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;

        try {
            // 执行请求并获得响应结果
            return getHttpClientResult(httpClient, httpPost);
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
        }
    }
    /**
     * 根据url下载文件，保存到filepath中
     *
     * @param url
     * @param filepath
     * @return
     */
    public static void doGetDownload(String url, String filepath) throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;
        InputStream inputStream = null;
        FileOutputStream fos = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpGet httpget = new HttpGet(url);

            httpget.setProtocolVersion(HttpVersion.HTTP_1_0);
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
            httpget.setConfig(requestConfig);

            httpResponse = httpClient.execute(httpget);
            HttpEntity entity = httpResponse.getEntity();
            inputStream = entity.getContent();
            long iimitSize = 1048576;
            long contentLength = httpResponse.getEntity().getContentLength();
            if (contentLength > iimitSize * 500) {
                throw new SjtbException(SjtbException.CodeInfo.sizeExc);
            }
            int size = 6 * 1024;
            BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(filepath));
            BufferedInputStream bis = new BufferedInputStream(inputStream, size);
            boolean flag = false;
            int len = 0;
            byte[] b = new byte[size];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
                flag = true;
            }
            if (!flag) {
                throw new RuntimeException(filepath + "下载到的文件未读取到内容");
            }
            bos.flush();
            bos.close();
            bis.close();
            //File file = new File(filepath);
            //file.getParentFile().mkdirs();
            //FileOutputStream fileout = new FileOutputStream(file);
            //byte[] buffer = new byte[10 * 1024];
            //int ch = 0;
            //while ((ch = is.read(buffer)) != -1) {
            //    fileout.write(buffer, 0, ch);
            //}
            //is.close();
            //fileout.flush();
            //fileout.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("下载文件失败!" + e.getMessage());
        }finally {
            // 释放资源
            release(httpResponse, httpClient);
            if (inputStream != null) inputStream.close();
            if (fos != null) fos.close();
        }
    }
    /**
     * post方式下载保存文件
     *
     * @param url
     * @param headers
     * @param params
     * @param jsonParam
     * @param fullFileName 保存的全路径名 fullFileName: F:\\ftpFile\\downloadWsxfZip\\ttt\\211122.zip
     * @throws Exception
     */
    public static void postDownload(String url, Map<String, String> headers, Map<String, String> params, String jsonParam, String fullFileName) throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;
        InputStream inputStream = null;
        FileOutputStream fos = null;
        try {
            // 创建http对象
            HttpPost httpPost = new HttpPost(url);
            httpPost.setProtocolVersion(HttpVersion.HTTP_1_0);
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
            httpPost.setConfig(requestConfig);
            // 设置请求头
            packageHeader(headers, httpPost);
            // 封装请求参数
            packageParam(params, httpPost);
            //body请求参数
            if (jsonParam != null) {
                httpPost.setEntity(new StringEntity(jsonParam, ENCODING));
            }
            // 执行请求并获得响应结果
            //return getHttpClientResult(httpClient, httpPost);
            // 执行请求
            httpResponse = httpClient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();
            //todo 超过500M拒绝?提示分包
            //if (inputStream.available() > 1048576 * 500) {
            //    throw new SjtbException(SjtbException.CodeInfo.sizeExc);
            //}
            long iimitSize = 1048576;
            long contentLength = httpResponse.getEntity().getContentLength();
            if (contentLength > iimitSize * 500) {
                throw new SjtbException(SjtbException.CodeInfo.sizeExc);
            }
            //String disposition = httpResponse.getFirstHeader("Content-Disposition").getValue();
            //String filename = disposition.substring(disposition.indexOf("filename=") + 9);
            //inputStream.available();
            long t1 = System.currentTimeMillis();
            int size = 6 * 1024;
            //File file = new File(fullFileName);
            //int length = 0;
            //fos = new FileOutputStream(file);
            //byte[] buffer = new byte[size];
            //while ((length = inputStream.read(buffer)) != -1) {
            //    fos.write(buffer, 0, length);
            //}
            //fos.flush();
            //BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fullFileName + filename));
            BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(fullFileName));
            BufferedInputStream bis = new BufferedInputStream(inputStream, size);
            boolean flag = false;
            int len = 0;
            byte[] b = new byte[size];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
                flag = true;
            }
            if (!flag) {
                throw new RuntimeException(fullFileName + "下载到的文件未读取到内容");
            }
            bos.flush();
            bos.close();
            bis.close();
            //File file = new File(fullFileName);
            //if (file.exists()) {
            //    if (file.length() > iimitSize * 6) {
            //        file.delete();
            //        throw new RuntimeException("数据包大小大于500M,需分包!");
            //    }
            //}
            //System.out.println((System.currentTimeMillis() - t1) / 1000 + "秒");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("下载文件失败!" + e.getMessage());
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
            if (inputStream != null) inputStream.close();
            if (fos != null) fos.close();
        }
    }


    /**
     * 发送put请求；不带请求参数
     *
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static String doPut(String url) throws Exception {
        return doPut(url);
    }

    /**
     * 发送put请求；带请求参数
     *
     * @param url    请求地址
     * @param params 参数集合
     * @return
     * @throws Exception
     */
    public static String doPut(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPut.setConfig(requestConfig);

        packageParam(params, httpPut);

        CloseableHttpResponse httpResponse = null;

        try {
            return getHttpClientResult(httpClient, httpPut);
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * 发送delete请求；不带请求参数
     *
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static String doDelete(String url) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpDelete.setConfig(requestConfig);

        CloseableHttpResponse httpResponse = null;
        try {
            return getHttpClientResult(httpClient, httpDelete);
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * 发送delete请求；带请求参数
     *
     * @param url    请求地址
     * @param params 参数集合
     * @return
     * @throws Exception
     */
    public static String doDelete(String url, Map<String, String> params) throws Exception {
        if (params == null) {
            params = new HashMap<String, String>();
        }

        params.put("_method", "delete");
        return doPost(url, params);
    }

    /**
     * Description: 封装请求头
     *
     * @param params
     * @param httpMethod
     */
    public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        // 封装请求头
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                // 设置到请求头到HttpRequestBase对象中
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Description: 封装请求参数
     *
     * @param params
     * @param httpMethod
     */
    public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod) throws UnsupportedEncodingException {
        // 封装请求参数
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<>();
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            // 设置到请求的http对象中
            httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
        }
    }

    /**
     * Description: 获得响应结果
     *
     * @param httpClient
     * @param httpMethod
     * @return
     * @throws Exception
     */
    public static String getHttpClientResult(CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
        // 执行请求
        CloseableHttpResponse httpResponse = httpClient.execute(httpMethod);
        // 获取返回结果
        if (httpResponse != null && httpResponse.getStatusLine() != null) {
            String content = "";
            if (httpResponse.getEntity() != null) {
                content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
            }
            return content;
        }
        return null;
    }

    /**
     * Description: 释放资源
     *
     * @param httpResponse
     * @param httpClient
     * @throws IOException
     */
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        // 释放资源
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }
}
